import { _decorator, Component, Node, } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('AIRobotControls')
export class AIRobotControls extends Component {

  // 是否正在移动
  isMove: boolean = false

  // 地图直径
  diameter: number = 0
  player: Node

  // 移动速度
  movementSpeed: number = 1

  angle: number = 0
  xRoutate: number = 0

  start() {
    this.diameter = this.node.parent.parent.children[0].getScale().x * 10
    this.player = this.node.parent.parent.children[1]
  }

  update(deltaTime: number) {
    this.createMoveEvent()
    this.updateMoveEvent()
    this.destroyMoveEvent()
  }

  createMoveEvent() {
    if (this.isMove) {
      return
    }

    // 随机方向
    const angleY: number = Math.random() * 360

    // 概率上下游
    let angleX: number = 0
    if (Math.random() > 0.2) {
      angleX = Math.random() * 90 - 45
    }

    this.angle = angleY + 90
    this.xRoutate = angleX

    // 开始移动
    this.isMove = true
  }

  updateMoveEvent() {
    if (!this.isMove) {
      return
    }

    const eulerAngles = this.node.eulerAngles
    eulerAngles.set(this.xRoutate, this.angle - 90, 0)
    this.node.eulerAngles = eulerAngles

    const pos = this.node.getPosition()
    // 移动速度受体型影响
    this.movementSpeed = Math.sqrt(this.node.getScale().x) / 3
    this.movementSpeed = Boolean(this.movementSpeed) ? this.movementSpeed : 1
    const moveLen = this.movementSpeed * 1

    const moveX = moveLen * Math.cos((2 * Math.PI / 360) * this.angle)
    const moveY = moveLen * Math.sin((2 * Math.PI / 360) * this.xRoutate)
    const moveZ = moveLen * Math.sin((2 * Math.PI / 360) * this.angle)
    pos.add3f(moveX, moveY, -moveZ)
    this.node.setPosition(pos)

  }

  destroyMoveEvent() {
    const pos = this.node.getPosition()
    const mapRadius = this.diameter / 2
    if (
      pos.x < -mapRadius || pos.x > mapRadius ||
      pos.z < -mapRadius || pos.z > mapRadius ||
      pos.y < 0 || pos.y > mapRadius
    ) {

      // 随机大小
      // 根据角色的大小上下浮动10 差值20
      const playerScale = this.node.parent.parent.children[1].getScale().x
      let scale = Math.random() * 5 - 2.5 + playerScale
      scale = scale < 0 ? 0.8 : scale
      scale /= (this.node.children[0].getScale().x / this.player.children[0].children[0].getScale().x)
      this.node.setScale(scale, scale, scale)

      // 随机起点坐标 距离角色方圆300
      const createRadius = 150
      const playerPos = this.player.getPosition()
      const x = playerPos.x + (Math.random() * createRadius * 2) - createRadius
      const z = playerPos.z + (Math.random() * createRadius * 2) - createRadius
      const y = Math.random() * createRadius
      const pos = this.node.getPosition()
      pos.x = x
      pos.z = z
      pos.y = y
      this.node.setPosition(pos)
      this.isMove = false

    }
  }
}


